﻿using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Browser;

using SBPweb.Messenger.Clients.Base;

namespace SBPweb.Messenger.ClientApplication.Controls
{

    public partial class Connection : UserControl
    {

        #region Private fields

        private Credentials credentials = new Credentials();

        #endregion

        #region Constructor logic

        public Connection()
        {
            InitializeComponent();
        }

        #endregion

        #region Property accessors

        public IConnectionManager Manager
        {
            get
            {
                return GetValue(ConnectionManagerProperty) as IConnectionManager;
            }
            set
            {
                SetValue(ConnectionManagerProperty, value as IConnectionManager);
            }
        }

        protected IAsyncConnectionManager AsyncManager
        {
            get
            {
                return Manager as IAsyncConnectionManager;
            }
        }

        #endregion

        #region Dependency properties

        public static DependencyProperty ConnectionManagerProperty = DependencyProperty.Register("ConnectionManager", typeof(IConnectionManager), typeof(Connection), new PropertyMetadata(null));

        #endregion

        #region Event handlers

        #region View handlers

        private void Connection_Loaded(object sender, RoutedEventArgs e)
        {
            if (!Manager.IsOnline)
            {
                PopupDialog.ShowDialog(credentials, "Sign in...", new RoutedEventHandler(pdLogin_OnClosed));
            }
            AsyncManager.EnumeratePresenceStatesCompleted += new System.EventHandler<ResultedAsyncCompletedEventArgs<List<string>>>(AsyncManager_EnumerateStatesCompleted);
            AsyncManager.EnumeratePresenceStatesAsync();
        }

        private void cbState_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            AsyncManager.SetPresenceStateAsync(cbState.SelectedItem.ToString());
        }

        private void pdLogin_OnClosed(object sender, RoutedEventArgs e)
        {
            AsyncManager.Connect(credentials.Values["UserName"].ToString(), credentials.Values["Password"].ToString());
        }

        #endregion

        #region Controller handlers

        private void AsyncManager_EnumerateStatesCompleted(object sender, ResultedAsyncCompletedEventArgs<List<string>> e)
        {
            e.Result.Sort();
            cbState.ItemsSource = e.Result;
        }

        #endregion

        #endregion

    }

}